#include <stdio.h>
#include <stdlib.h>

struct list
{
    struct list *next;
    struct list *prev;
    int data;
};

void add_data(struct list *head, int data)
{
    struct list *new;
    new = malloc(sizeof(struct list));
    new->data = data;

    struct list *tmp = head;
    while (tmp->next != NULL)
    {
        tmp = tmp->next;
    }

    tmp->next = new;

    new->next = NULL;
    new->prev = tmp;
}

void show(struct list *head)
{
    struct list *tmp;
    tmp = head->next;
    while (tmp != NULL)
    {
        printf("%d ", tmp->data);
        tmp = tmp->next;
    }

    printf("\n");
}

void swap(struct list *head, int x, int y)
{
    if (x == y)
    {
        // 如果两个值相同，无需交换
        return;
    }

    struct list *first = NULL, *second = NULL;
    struct list *tmp = head->next; // tmp 指向第一个实际节点

    // 找到值为 x 和 y 的节点
    while (tmp != NULL)
    {
        if (tmp->data == x)
        {
            first = tmp;
        }
        if (tmp->data == y)
        {
            second = tmp;
        }
        tmp = tmp->next;
    }

    // 如果找不到对应值的节点，直接返回
    if (first == NULL || second == NULL)
    {
        printf("One or both values not found in the list.\n");
        return;
    }

    // 交换节点
    if (first->prev != NULL)
    {
        first->prev->next = second;
    }
    else
    {
        head->next = second;
    }

    if (second->prev != NULL)
    {
        second->prev->next = first;
    }
    else
    {
        head->next = first;
    }

    struct list *tmp_next = first->next;
    first->next = second->next;
    second->next = tmp_next;

    struct list *tmp_prev = first->prev;
    first->prev = second->prev;
    second->prev = tmp_prev;
}

int main()
{
    struct list *head;
    head = malloc(sizeof(struct list));
    head->next = head->prev = NULL;

    add_data(head, 1);
    add_data(head, 2);
    add_data(head, 3);
    add_data(head, 4);
    add_data(head, 5);
    add_data(head, 6);
    add_data(head, 7);
    add_data(head, 8);
    show(head);

    swap(head, 2, 6);
    show(head);

    return 0;
}
